#include "stdafx.h"
#include "HierachySystem.h"

#include "HierachyComponent.h"


namespace Be
{
	HierachyNode::HierachyNode(Entity* p_pEntity)
		: Node(p_pEntity)
	{
		m_pHierachyComponent.Initialize(p_pEntity);
	}

	HierachyNode::~HierachyNode()
	{
	}
}

namespace Be
{
	HierachySystem::HierachySystem()
	{
	}

	HierachySystem::~HierachySystem()
	{
	}

	HierachySystem& HierachySystem::Inst()
	{
		static HierachySystem l_Instance;

		return l_Instance;
	}

	void HierachySystem::OnRegister(HierachyNode* p_pNode, const HierachyNode::Seed& p_rSeed)
	{
		assert(p_pNode != 0);

		if(p_rSeed.m_pParent != 0)
		{
			HierachyNode* l_pParentNode = GetNode(p_rSeed.m_pParent);
			assert(l_pParentNode != 0 && l_pParentNode->m_pHierachyComponent != 0);

			p_pNode->m_pHierachyComponent->SetParent(l_pParentNode->m_pHierachyComponent);
			l_pParentNode->m_pHierachyComponent->AddChild(p_pNode->m_pHierachyComponent);
		}
	}

	void HierachySystem::OnUnregister(HierachyNode* p_pNode)
	{
		assert(p_pNode != 0);

		ComPtr<HierachyComponent> l_pParent = p_pNode->m_pHierachyComponent->GetParent();
		if(l_pParent != 0)
		{
			p_pNode->m_pHierachyComponent->SetParent(0);
			l_pParent->RemoveChild(p_pNode->m_pHierachyComponent);
		}
		
		std::set<ComPtr<HierachyComponent>>& l_ChildSet = p_pNode->m_pHierachyComponent->GetChildSet();

		std::set<ComPtr<HierachyComponent>>::iterator l_Iter = l_ChildSet.begin();
		while(l_Iter != l_ChildSet.end())
		{
			std::set<ComPtr<HierachyComponent>>::iterator l_CurIter = l_Iter;
			++l_Iter;

			ComPtr<HierachyComponent> l_pChild = *l_CurIter;
			assert(l_pChild != 0);

			l_pChild->SetParent(0);
		}

		l_ChildSet.clear();
	}

	void HierachySystem::OnUpdate(HierachyNode* p_pNode)
	{
		assert(p_pNode != 0);
	}
}
